import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'dart:io';

// 添加全局 navigator key
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  try {
    // 确保 Flutter 绑定初始化
    WidgetsFlutterBinding.ensureInitialized();
    debugPrint('Flutter 绑定初始化完成');

    // 先初始化 SharedPreferences
    debugPrint('初始化 SharedPreferences...');
    try {
      await SharedPreferences.getInstance();
      debugPrint('SharedPreferences 初始化成功');
    } catch (e) {
      debugPrint('SharedPreferences 初始化失败: $e');
      // 继续执行，因为我们可能不需要立即使用 SharedPreferences
    }

    // 初始化通知
    debugPrint('开始初始化通知...');
    try {
      final initialized = await AwesomeNotifications().initialize(
        null, // 不使用自定义图标
        [
          NotificationChannel(
            channelKey: 'todo_channel',
            channelName: 'Todo Notifications',
            channelDescription: 'Notification channel for todo reminders',
            defaultColor: Colors.teal,
            ledColor: Colors.teal,
            importance: NotificationImportance.High,
            defaultRingtoneType: DefaultRingtoneType.Notification,
            locked: false, // 允许用户修改通知设置
            enableVibration: true,
            playSound: true,
            criticalAlerts: false, // 默认不启用关键提醒
            enableLights: true,
          )
        ],
        debug: kDebugMode, // 根据是否为调试模式设置
      );
      debugPrint('通知初始化结果: $initialized');

      if (initialized) {
        // 请求通知权限
        debugPrint('检查通知权限...');
        final isAllowed = await AwesomeNotifications().isNotificationAllowed();
        debugPrint('通知权限状态: $isAllowed');

        if (!isAllowed) {
          debugPrint('通知权限未授予');
        }

        // 设置通知操作监听器
        debugPrint('设置通知监听器...');
        AwesomeNotifications().setListeners(
          onActionReceivedMethod: onActionReceivedMethod,
          onNotificationCreatedMethod: onNotificationCreatedMethod,
          onNotificationDisplayedMethod: onNotificationDisplayedMethod,
          onDismissActionReceivedMethod: onDismissActionReceivedMethod,
        );

        // 创建持久通知
        if (isAllowed) {
          debugPrint('创建持久通知...');
          try {
            await AwesomeNotifications().createNotification(
              content: NotificationContent(
                id: 1,
                channelKey: 'todo_channel',
                title: 'Todo List 正在运行',
                body: '保持提醒功能正常运行',
                locked: true,
                autoDismissible: false,
                category: NotificationCategory.Service,
              ),
            );
            debugPrint('持久通知创建成功');
          } catch (e) {
            debugPrint('创建持久通知失败: $e');
          }
        }
      } else {
        debugPrint('通知初始化失败');
      }
    } catch (e) {
      debugPrint('通知初始化过程中出错: $e');
    }

    runApp(const MyApp());
  } catch (e, stackTrace) {
    debugPrint('初始化错误: $e');
    debugPrint('堆栈跟踪: $stackTrace');
    // 即使发生错误也要运行应用
    runApp(const MyApp());
  }
}

// 通知操作回调方法
@pragma('vm:entry-point')
Future<void> onActionReceivedMethod(ReceivedAction receivedAction) async {
  if (receivedAction.payload != null &&
      receivedAction.payload!['todo_id'] != null) {
    debugPrint('收到通知操作: ${receivedAction.payload}');
    // 使用静态方法处理通知操作
    await TodoListScreen.handleNotificationAction(receivedAction);
  }
}

@pragma('vm:entry-point')
Future<void> onNotificationCreatedMethod(
    ReceivedNotification receivedNotification) async {
  debugPrint('通知已创建');
}

@pragma('vm:entry-point')
Future<void> onNotificationDisplayedMethod(
    ReceivedNotification receivedNotification) async {
  debugPrint('通知已显示');
}

@pragma('vm:entry-point')
Future<void> onDismissActionReceivedMethod(
    ReceivedAction receivedAction) async {
  debugPrint('通知已关闭');
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey, // 添加 navigator key
      title: 'Todo List',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.teal,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
        inputDecorationTheme: InputDecorationTheme(
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: const BorderSide(color: Colors.teal, width: 2),
          ),
        ),
      ),
      home: const TodoListScreen(),
    );
  }
}

class TodoListScreen extends StatefulWidget {
  const TodoListScreen({super.key});

  // 添加静态方法处理通知操作
  static Future<void> handleNotificationAction(
      ReceivedAction receivedAction) async {
    // 获取全局 navigator key
    final context = navigatorKey.currentContext;
    if (context == null) return;

    // 获取当前的 TodoListScreen state
    final state = context.findAncestorStateOfType<_TodoListScreenState>();
    if (state == null) return;

    final todoId = receivedAction.payload!['todo_id'];
    final todo = state._todos.firstWhere(
      (todo) => todo.createdAt.millisecondsSinceEpoch.toString() == todoId,
      orElse: () => Todo(title: ''),
    );

    if (todo.title.isNotEmpty) {
      state._showDetailsDialog(todo);
    }
  }

  @override
  State<TodoListScreen> createState() => _TodoListScreenState();
}

class _TodoListScreenState extends State<TodoListScreen> {
  final List<Todo> _todos = [];
  final TextEditingController _textController = TextEditingController();
  final TextEditingController _searchController = TextEditingController();
  DateTime? _selectedDate;
  bool _isSearching = false;
  TodoPriority _selectedPriority = TodoPriority.low;
  final Set<String> _expandedItems = {};
  bool _hasNotificationPermission = false;

  @override
  void initState() {
    super.initState();
    _loadTodos();
    _checkNotificationPermission();
  }

  Future<void> _checkNotificationPermission() async {
    final isAllowed = await AwesomeNotifications().isNotificationAllowed();
    setState(() {
      _hasNotificationPermission = isAllowed;
    });
  }

  Future<void> _requestNotificationPermission() async {
    final isAllowed =
        await AwesomeNotifications().requestPermissionToSendNotifications();

    setState(() {
      _hasNotificationPermission = isAllowed;
    });

    if (isAllowed) {
      // 权限获取后，创建持久通知
      await AwesomeNotifications().createNotification(
        content: NotificationContent(
          id: 1,
          channelKey: 'todo_channel',
          title: 'Todo List 正在运行',
          body: '保持提醒功能正常运行',
          locked: true,
          autoDismissible: false,
          category: NotificationCategory.Service,
        ),
      );
    }
  }

  // 加载待办事项
  Future<void> _loadTodos() async {
    final prefs = await SharedPreferences.getInstance();
    final String? todosString = prefs.getString('todos');
    if (todosString != null) {
      final List<dynamic> decoded = jsonDecode(todosString);
      setState(() {
        _todos.clear();
        _todos.addAll(
          decoded.map((item) => Todo.fromJson(item)).toList(),
        );
      });
    }
  }

  // 保存待办事项
  Future<void> _saveTodos() async {
    final prefs = await SharedPreferences.getInstance();
    final String encoded = jsonEncode(_todos.map((t) => t.toJson()).toList());
    await prefs.setString('todos', encoded);
  }

  List<Todo> get _filteredTodos {
    return _todos.where((todo) {
      // 关键字搜索
      final searchText = _searchController.text.toLowerCase();
      final titleMatches = todo.title.toLowerCase().contains(searchText);

      // 日期过滤
      final dateMatches = _selectedDate == null ||
          (todo.createdAt.year == _selectedDate!.year &&
              todo.createdAt.month == _selectedDate!.month &&
              todo.createdAt.day == _selectedDate!.day);

      return titleMatches && dateMatches;
    }).toList();
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  void _addTodo(String title) {
    if (title.isEmpty) return;

    setState(() {
      _todos.add(Todo(
        title: title,
        priority: _selectedPriority,
      ));
      _textController.clear();
      _selectedPriority = TodoPriority.low; // 重置优先级
    });
    _saveTodos();
  }

  void _toggleTodo(int index) async {
    setState(() {
      _todos[index].isCompleted = !_todos[index].isCompleted;
    });
    if (_todos[index].isCompleted) {
      await _cancelNotification(_todos[index]);
    } else if (_todos[index].dueDate != null) {
      await _scheduleNotification(_todos[index]);
    }
    _saveTodos();
  }

  void _deleteTodo(int index) async {
    // 显示确认对话框
    final bool? confirm = await showDialog<bool>(
      context: navigatorKey.currentContext!,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个待办事项吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(
              foregroundColor: Theme.of(context).colorScheme.error,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirm == true) {
      // 获取要删除的待办事项
      final todoToDelete = _filteredTodos[index];
      // 在原始列表中找到对应的索引
      final originalIndex = _todos.indexWhere((todo) =>
          todo.createdAt.millisecondsSinceEpoch ==
          todoToDelete.createdAt.millisecondsSinceEpoch);

      if (originalIndex != -1) {
        // 移除对_cancelNotification的调用
        setState(() {
          _todos.removeAt(originalIndex);
        });
        _saveTodos();
      }
    }
  }

  void _onReorder(int oldIndex, int newIndex) {
    setState(() {
      if (newIndex > oldIndex) {
        newIndex -= 1;
      }
      final item = _todos.removeAt(oldIndex);
      _todos.insert(newIndex, item);
    });
    _saveTodos();
  }

  Future<void> _selectDueDate(Todo todo) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: todo.dueDate ?? DateTime.now(),
      firstDate: DateTime.now(),
      lastDate: DateTime(2100),
    );

    if (picked != null) {
      final TimeOfDay? time = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(todo.dueDate ?? DateTime.now()),
      );

      if (time != null) {
        setState(() {
          todo.dueDate = DateTime(
            picked.year,
            picked.month,
            picked.day,
            time.hour,
            time.minute,
          );
        });
        // 设置提醒
        await _scheduleNotification(todo);
        _saveTodos();
      }
    }
  }

  // 显示详情对话框
  void _showDetailsDialog(Todo todo) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height * 0.7,
              maxWidth: MediaQuery.of(context).size.width * 0.8,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text(
                  todo.title,
                  style: Theme.of(context).textTheme.titleLarge,
                ),
                const SizedBox(height: 16),
                // 内容区域
                Flexible(
                  child: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(Icons.flag, color: todo.priority.color),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                '优先级: ${todo.priority.label}',
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            const Icon(Icons.access_time),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                '创建时间: ${_formatDateTime(todo.createdAt)}',
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                        if (todo.dueDate != null) ...[
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Icon(
                                Icons.calendar_today,
                                color: todo.dueDate!.isBefore(DateTime.now())
                                    ? Colors.red
                                    : null,
                              ),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  '截止时间: ${_formatDateTime(todo.dueDate!)}',
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    color:
                                        todo.dueDate!.isBefore(DateTime.now())
                                            ? Colors.red
                                            : null,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
                // 按钮区域
                const SizedBox(height: 16),
                Align(
                  alignment: Alignment.centerRight,
                  child: TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('关闭'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  // 设置提醒
  Future<void> _scheduleNotification(Todo todo) async {
    if (todo.dueDate == null) return;

    final now = DateTime.now();
    final scheduledDate = todo.dueDate!;

    // 如果截止时间已过，不设置提醒
    if (scheduledDate.isBefore(now)) return;

    // 计算提前 15 分钟的提醒时间
    final reminderTime = scheduledDate.subtract(const Duration(minutes: 15));

    // 如果提醒时间已过，直接返回
    if (reminderTime.isBefore(now)) return;

    // 确保有通知权限
    if (!_hasNotificationPermission) {
      await _requestNotificationPermission();
      if (!_hasNotificationPermission) return;
    }

    try {
      // 使用时间戳来调度通知
      final int scheduleTime = reminderTime.millisecondsSinceEpoch;

      await AwesomeNotifications().createNotification(
        content: NotificationContent(
          id: todo.createdAt.millisecondsSinceEpoch.remainder(100000),
          channelKey: 'todo_channel',
          title: '待办事项提醒',
          body: '${todo.title}\n将在 15 分钟后到期',
          notificationLayout: NotificationLayout.Default,
          category: NotificationCategory.Reminder,
          wakeUpScreen: true,
          criticalAlert: true,
          autoDismissible: false,
          payload: {
            'todo_id': todo.createdAt.millisecondsSinceEpoch.toString(),
          },
        ),
        actionButtons: [
          NotificationActionButton(
            key: 'MARK_DONE',
            label: '标记完成',
          ),
        ],
        schedule: NotificationCalendar.fromDate(
          date: reminderTime,
          allowWhileIdle: true,
          preciseAlarm: true,
        ),
      );
      debugPrint('成功设置提醒: ${todo.title} 在 ${_formatDateTime(reminderTime)}');
    } catch (e) {
      debugPrint('设置提醒失败: $e');
    }
  }

  // 取消提醒
  Future<void> _cancelNotification(Todo todo) async {
    await AwesomeNotifications().cancel(
      todo.createdAt.millisecondsSinceEpoch.remainder(100000),
    );
  }

  Widget _buildTodoCard(Todo todo) {
    final bool isOverdue =
        todo.dueDate != null && todo.dueDate!.isBefore(DateTime.now());

    return Dismissible(
      key: ValueKey('${todo.createdAt.millisecondsSinceEpoch}_${todo.title}'),
      direction: DismissDirection.endToStart,
      confirmDismiss: (direction) async {
        // 显示确认对话框
        return await showDialog<bool>(
          context: navigatorKey.currentContext!,
          builder: (context) => AlertDialog(
            title: const Text('确认删除'),
            content: const Text('确定要删除这个待办事项吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                style: TextButton.styleFrom(
                  foregroundColor: Theme.of(context).colorScheme.error,
                ),
                child: const Text('删除'),
              ),
            ],
          ),
        );
      },
      onDismissed: (direction) {
        // 获取要删除的待办事项在原始列表中的索引
        final originalIndex = _todos.indexWhere((t) =>
            t.createdAt.millisecondsSinceEpoch ==
            todo.createdAt.millisecondsSinceEpoch);

        if (originalIndex != -1) {
          // 移除对_cancelNotification的调用
          setState(() {
            _todos.removeAt(originalIndex);
          });
          _saveTodos();
        }
      },
      background: Container(
        color: Theme.of(context).colorScheme.error,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 16),
        child: const Icon(
          Icons.delete,
          color: Colors.white,
        ),
      ),
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
        elevation: 2,
        child: InkWell(
          onTap: () => _showDetailsDialog(todo),
          child: Padding(
            padding: const EdgeInsets.only(left: 8, right: 16),
            child: Row(
              children: [
                // 拖动手柄
                Icon(
                  Icons.drag_handle,
                  color: Colors.grey[400],
                  size: 20,
                ),
                // 复选框
                Transform.scale(
                  scale: 0.9,
                  child: Checkbox(
                    value: todo.isCompleted,
                    onChanged: (_) => _toggleTodo(_todos.indexOf(todo)),
                    activeColor: Theme.of(context).colorScheme.primary,
                  ),
                ),
                // 主要内容区域
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 标题行
                        Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 6,
                                vertical: 2,
                              ),
                              decoration: BoxDecoration(
                                color: todo.priority.color.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(4),
                                border: Border.all(
                                  color: todo.priority.color,
                                  width: 1,
                                ),
                              ),
                              child: Text(
                                todo.priority.label,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: todo.priority.color,
                                ),
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                todo.title,
                                style: TextStyle(
                                  fontSize: 16,
                                  decoration: todo.isCompleted
                                      ? TextDecoration.lineThrough
                                      : null,
                                  color: todo.isCompleted
                                      ? Colors.grey
                                      : Theme.of(context).colorScheme.onSurface,
                                ),
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                        // 截止时间行
                        if (todo.dueDate != null) ...[
                          const SizedBox(height: 4),
                          Row(
                            children: [
                              Icon(
                                Icons.calendar_today,
                                size: 14,
                                color:
                                    isOverdue ? Colors.red : Colors.grey[600],
                              ),
                              const SizedBox(width: 4),
                              Text(
                                _formatDateTime(todo.dueDate!),
                                style: TextStyle(
                                  fontSize: 12,
                                  color:
                                      isOverdue ? Colors.red : Colors.grey[600],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ],
                    ),
                  ),
                ),
                // 操作按钮区
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 设置截止时间
                    IconButton(
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(
                        minWidth: 40,
                        minHeight: 40,
                      ),
                      icon: Icon(
                        Icons.calendar_month,
                        size: 20,
                        color: todo.dueDate != null
                            ? Theme.of(context).colorScheme.primary
                            : Colors.grey,
                      ),
                      onPressed: () => _selectDueDate(todo),
                    ),
                    // 设置优先级
                    PopupMenuButton<TodoPriority>(
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(
                        minWidth: 40,
                        minHeight: 40,
                      ),
                      icon: Icon(
                        Icons.flag,
                        size: 20,
                        color: todo.priority.color,
                      ),
                      onSelected: (TodoPriority priority) {
                        setState(() {
                          todo.priority = priority;
                        });
                        _saveTodos();
                      },
                      itemBuilder: (context) => TodoPriority.values
                          .map(
                            (priority) => PopupMenuItem(
                              value: priority,
                              child: Row(
                                children: [
                                  Icon(Icons.flag, color: priority.color),
                                  const SizedBox(width: 8),
                                  Text(priority.label),
                                ],
                              ),
                            ),
                          )
                          .toList(),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        elevation: 2,
        title: _isSearching
            ? TextField(
                controller: _searchController,
                autofocus: true,
                decoration: InputDecoration(
                  hintText: '搜索任务...',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey[400]),
                ),
                style: const TextStyle(color: Colors.black87, fontSize: 16),
                onChanged: (_) => setState(() {}),
              )
            : const Text('Todo List'),
        actions: [
          // 通知权限按钮
          if (!_hasNotificationPermission)
            IconButton(
              icon: const Icon(Icons.notifications_off),
              onPressed: _requestNotificationPermission,
              tooltip: '开启通知权限',
            ),
          // 日期筛选按钮
          IconButton(
            icon: Icon(
              Icons.calendar_today,
              color: _selectedDate != null
                  ? Theme.of(context).colorScheme.primary
                  : null,
            ),
            onPressed: () => _selectDate(context),
          ),
          // 搜索按钮
          IconButton(
            icon: Icon(_isSearching ? Icons.close : Icons.search),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchController.clear();
                }
              });
            },
          ),
        ],
        bottom: _selectedDate != null
            ? PreferredSize(
                preferredSize: const Size.fromHeight(40),
                child: Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 8.0),
                  child: Row(
                    children: [
                      Icon(
                        Icons.date_range,
                        size: 16,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        '${_selectedDate!.year}-${_selectedDate!.month.toString().padLeft(2, '0')}-${_selectedDate!.day.toString().padLeft(2, '0')}',
                        style: TextStyle(
                          color: Theme.of(context).colorScheme.primary,
                        ),
                      ),
                      const Spacer(),
                      IconButton(
                        icon: const Icon(Icons.clear, size: 18),
                        onPressed: () => setState(() {
                          _selectedDate = null;
                        }),
                      ),
                    ],
                  ),
                ),
              )
            : null,
      ),
      body: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surface,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.1),
                  spreadRadius: 1,
                  blurRadius: 3,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textController,
                    decoration: InputDecoration(
                      hintText: '添加新任务...',
                      prefixIcon: const Icon(Icons.task),
                      suffixIcon: PopupMenuButton<TodoPriority>(
                        icon: Icon(
                          Icons.flag,
                          color: _selectedPriority.color,
                        ),
                        onSelected: (TodoPriority priority) {
                          setState(() {
                            _selectedPriority = priority;
                          });
                        },
                        itemBuilder: (context) => TodoPriority.values
                            .map(
                              (priority) => PopupMenuItem(
                                value: priority,
                                child: Row(
                                  children: [
                                    Icon(Icons.flag, color: priority.color),
                                    const SizedBox(width: 8),
                                    Text(priority.label),
                                  ],
                                ),
                              ),
                            )
                            .toList(),
                      ),
                      filled: true,
                      fillColor: Theme.of(context).colorScheme.surface,
                    ),
                    onSubmitted: _addTodo,
                  ),
                ),
                const SizedBox(width: 12),
                Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.add, color: Colors.white),
                    onPressed: () => _addTodo(_textController.text),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: ReorderableListView(
              onReorder: _onReorder,
              children: _filteredTodos.map(_buildTodoCard).toList(),
            ),
          ),
        ],
      ),
    );
  }
}

enum TodoPriority {
  low,
  medium,
  high;

  Color get color {
    switch (this) {
      case TodoPriority.low:
        return Colors.green;
      case TodoPriority.medium:
        return Colors.orange;
      case TodoPriority.high:
        return Colors.red;
    }
  }

  String get label {
    switch (this) {
      case TodoPriority.low:
        return '低';
      case TodoPriority.medium:
        return '中';
      case TodoPriority.high:
        return '高';
    }
  }
}

class Todo {
  String title;
  bool isCompleted;
  DateTime createdAt;
  TodoPriority priority;
  DateTime? dueDate;

  Todo({
    required this.title,
    this.isCompleted = false,
    DateTime? createdAt,
    this.priority = TodoPriority.low,
    this.dueDate,
  }) : createdAt = createdAt ?? DateTime.now();

  // 从 JSON 转换为 Todo 对象
  factory Todo.fromJson(Map<String, dynamic> json) {
    return Todo(
      title: json['title'] as String,
      isCompleted: json['isCompleted'] as bool,
      createdAt: DateTime.parse(json['createdAt'] as String),
      priority: TodoPriority.values[json['priority'] as int],
      dueDate: json['dueDate'] != null ? DateTime.parse(json['dueDate']) : null,
    );
  }

  // 将 Todo 对象转换为 JSON
  Map<String, dynamic> toJson() {
    return {
      'title': title,
      'isCompleted': isCompleted,
      'createdAt': createdAt.toIso8601String(),
      'priority': priority.index,
      'dueDate': dueDate?.toIso8601String(),
    };
  }
}
